import { PLAYER_UPDATE_ATTRS } from './Enums/index'
import EventManager from './EventManager'
import GameMgr from './GameManager'
import Bignumber from './utils/bignumber'
export default class Role extends cc.Component {
  private _rolename: string = ''
  // 人物属性
  ATK: number = 10

  HP: number = 100

  HPRE: number = 1

  ASPD: number = 1

  CRT: number = 0.1

  CRTCHANCE: number = 0.1

  isDead: boolean = false

  bulletSpriteFrame: cc.SpriteFrame = null

  waitQueue: Promise<any>[] = []

  bullet: cc.Node = null

  async init() {
    await this.changeRole('default')
    EventManager.on(PLAYER_UPDATE_ATTRS.ATK, this.changeATK, this)
    EventManager.on(PLAYER_UPDATE_ATTRS.HP, this.changeHp, this)
    EventManager.on(PLAYER_UPDATE_ATTRS.HPRE, this.changeHPRE, this)
    EventManager.on(PLAYER_UPDATE_ATTRS.ASPD, this.changeASPD, this)
    EventManager.on(PLAYER_UPDATE_ATTRS.CRT, this.changeCRT, this)
    EventManager.on(PLAYER_UPDATE_ATTRS.CRTCHANCE, this.changeCRTCHANCE, this)
  }

  reset() {
    this.ATK = 10
    this.HP = 100
    this.HPRE = 1
    this.ASPD = 1
    this.CRT = 0.1
    this.CRTCHANCE = 0.1
    this.isDead = false
    this.roleName = 'default'
  }

  changeATK() {
    this.ATK = Bignumber(this.ATK).plus(Bignumber(1))
    GameMgr.instance.totalPowerLabel.string = '战力：' + this.ATK
    const node = this.getConetntNodeByName(PLAYER_UPDATE_ATTRS.ATK)
    node.string = this.ATK + ''
  }

  changeHp() {
    this.HP = Bignumber(this.HP).plus(Bignumber(1))
    const node = this.getConetntNodeByName(PLAYER_UPDATE_ATTRS.HP)
    node.string = this.HP + ''
  }

  changeHPRE() {
    this.HPRE = Bignumber(this.HPRE).plus(Bignumber(0.1))
    const node = this.getConetntNodeByName(PLAYER_UPDATE_ATTRS.HPRE)
    node.string = this.HPRE + ''
  }

  changeASPD() {
    this.ASPD = Bignumber(this.ASPD).plus(Bignumber(0.1))
    const node = this.getConetntNodeByName(PLAYER_UPDATE_ATTRS.ASPD)
    node.string = this.ASPD + ''
  }

  changeCRT() {
    this.CRT = Bignumber(this.CRT).plus(Bignumber(0.1))
    const node = this.getConetntNodeByName(PLAYER_UPDATE_ATTRS.CRT)
    node.string = this.CRT + ''
  }

  changeCRTCHANCE() {
    this.CRTCHANCE = Bignumber(this.CRTCHANCE).plus(Bignumber(0.1))
    const node = this.getConetntNodeByName(PLAYER_UPDATE_ATTRS.CRTCHANCE)
    node.string = this.CRTCHANCE + ''
  }

  get roleName() {
    return this._rolename
  }

  set roleName(val: string) {
    if (this._rolename === val) return
    this._rolename = val
    this.changeRole(this._rolename)
  }

  /**
   * 切换人物皮肤
   * GameMgr.instance.roleInstance.roleName = 'role01'
   * 切换人物动作
   * GameMgr.instance.roleAnimation.play('attack')
   * @param url 路径
   */
  async changeRole(url: string) {
    this.waitQueue = [this.loadBullet(url), this.loadRole(url)]
    await Promise.all(this.waitQueue)
    this.waitQueue = []
  }

  loadBullet(url: string) {
    return new Promise((resolve, reject) => {
      cc.resources.load(`image/roles/${url}/bullet`, cc.SpriteFrame, (err, sprite: cc.SpriteFrame) => {
        if (!err) {
          this.bulletSpriteFrame = sprite
          resolve(true)
          return
        }
        console.error(err)
        reject(err)
      })
    })
  }

  loadRole(url: string) {
    return new Promise((resolve, reject) => {
      cc.resources.load(`prefab/roles/${url}`, cc.Prefab, (err, prefab: cc.Prefab) => {
        if (!err) {
          const node = cc.instantiate(prefab)
          node.setPosition(-300, 200)
          GameMgr.instance.roleNode?.destroy()
          GameMgr.instance.roleNode = node
          GameMgr.instance.layoutTop.addChild(node)
          GameMgr.instance.roleAnimation = node.getComponent(cc.Animation)
          GameMgr.instance.roleAnimation.on(cc.Animation.EventType.FINISHED, this.onAnimationFinished)
          GameMgr.instance.roleAnimation.play('run')
          resolve(true)
          return
        }
        console.error(err)
        reject(err)
      })
    })
  }

  onAnimationFinished() {
    GameMgr.instance.roleAnimation.play('run')
  }

  /**
   * 生成子弹
   *
   */
  addBullet() {
    const bullet = new cc.Node()
    bullet.setContentSize(40, 25)
    bullet.setPosition(-225, 185)
    GameMgr.instance.layoutTop.addChild(bullet)
    const sprite = bullet.addComponent(cc.Sprite)
    // 必须设置为custom才能更改宽高
    sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM
    sprite.spriteFrame = this.bulletSpriteFrame
    this.bullet = bullet
    return bullet
  }

  getConetntNodeByName(name: string) {
    const content = GameMgr.instance.pannelContent
    return content.getChildByName(name).getChildByName('num_label').getComponent(cc.Label) || null
  }

  getHurtHP(node) {
    const progressBar = node.getComponentInChildren(cc.ProgressBar)
    progressBar.node.active = true
    const bar = progressBar.getComponentInChildren(cc.Sprite)
    const label = node.getComponentInChildren(cc.Label)
    const roleDamage = GameMgr.instance.roleInstance.ATK
    label.node.active = true
    label.string = roleDamage
    cc.tween(label.node)
      .to(0.3, { position: new cc.Vec2(0, 90), scale: 1.5 })
      .call(() => {
        label.node.active = false
        label.node.position = new cc.Vec2(0, 70)
      })
      .start()
    this.HP -= roleDamage
    bar.fillRange = this.HP / 100
    if (this.HP <= 0) {
      this.isDead = true
      console.log('主角死亡了～')
    }
  }
}
